<template>
  <div id="login">
    <div class="login-box">
      <!-- 头像区域 -->
      <div class="login-head">
        <img src="../../assets/img/head.jpg" alt />
      </div>
      <!-- 表达区域 -->
      <el-form
        label-width="0px"
        class="login-from"
        :model="loginForm"
        :rules="loginFromRules"
        ref="loginFormRef"
      >
        <el-form-item prop="username">
          <el-input prefix-icon="el-icon-user" v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input prefix-icon="el-icon-key" v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      //表单数据绑定对象
      loginForm: {
        username: "admin",
        password: "123456"
      },
      //表单规则绑定对象
      loginFromRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    resetLoginForm() {
      //重置表单
      this.$refs.loginFormRef.resetFields();
    },
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return;

        const { data: res } = await this.$http.post("login", this.loginForm);

        if (res.meta.status !== 200) {
          return this.$message.error("登录失败！");
        } else {
          this.$message.success("登录成功");
        }
        //登录成功后将token保存到sessionStorage中
        //项目中除了登录接口  其他api接口必须登录后才能访问
        //token应当只在当前打开网页有效 所以保存到sessionStorage中
        window.sessionStorage.setItem("token", res.data.token);
        //成功后跳转到home界面
        this.$router.push("/home");
      });
    }
  }
};
</script>

<style lang='less' scoped>
#login {
  height: 100%;
  background: #2b4b6b;
}

.login-box {
  width: 450px;
  height: 300px;
  background: #ffffff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.login-head {
  width: 130px;
  height: 130px;
  border: 1px solid #eeeeee;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 0 10px #dddddd;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #ffffff;

  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
.login-from {
  position: absolute;
  bottom: 0px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 30px;
}
.btns {
  float: right;
}
</style>